import java.util.*;

public class Main {

    //团建
    static int N = 2 * 100000 + 10;
    static int n, m, res;
    static int[] a = new int[N];
    static int[] b = new int[N];
    static List<Integer>[] G1 = new List[N];
    static List<Integer>[] G2 = new List[N];

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        //n , m 为两人树的大小
        n = sc.nextInt();
        m = sc.nextInt();
        //每个节点的值
        for (int i = 1; i <= n; i++)
            a[i] = sc.nextInt();
        for (int i = 1; i <= m; i++)
            b[i] = sc.nextInt();

        //构建树
        for (int i = 1; i <= n; i++)
            G1[i] = new ArrayList<>();
        for (int i = 1; i <= m; i++)
            G2[i] = new ArrayList<>();

        for (int i = 2; i <= n; i++) {
            int u = sc.nextInt();
            int v = sc.nextInt();
            G1[u].add(v);
            G1[v].add(u);
        }
        for (int i = 2; i <= m; i++) {
            int u = sc.nextInt();
            int v = sc.nextInt();
            G2[u].add(v);
            G2[v].add(u);
        }
        if (a[1] != b[1]) {
            System.out.println(0);
            return;
        }
        dfs(1, 0, 1, 0, 1);
        System.out.println(res);
    }

    public static void dfs(int u1, int far1, int u2, int far2, int dep) {
        res = Math.max(res, dep);
        Map<Integer, Integer> mp = new HashMap<>();
        for (int v : G1[u1]) {
            if (v == far1)
                continue;
            mp.put(a[v], v);
        }
        for (int v : G2[u2]) {
            if (v == far2)
                continue;
            if (mp.containsKey(b[v]))
                dfs(mp.get(b[v]), u1, v, u2, dep + 1);
        }
    }
}
